import { getUpDownDay } from '@/utils';
import { Button, Checkbox, message, Table, TimePicker } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { YmDialog } from 'ym-design';
import OStyle from './index.less';
type positionInfoValue = any[];
interface SelectWeekDaysProps {
  value?: positionInfoValue;
  onChange?: (newVal: positionInfoValue) => void;
}
const SelectWeekDays: React.FC<SelectWeekDaysProps> = (props) => {
  const { value, onChange } = props;
  const [isModalOpen, setIsModalOpen] = useState(false);
  let [tableKey, setTableKey] = useState<number>(0);
  const [weekData, setWeekData] = useState<any[]>([]);
  const [weekList, setWeekList] = useState<any[]>([
    { label: '一', value: '1', checked: false, startTrainTime: '', endTrainTime: '', status: '' },
    { label: '二', value: '2', checked: false, startTrainTime: '', endTrainTime: '', status: '' },
    { label: '三', value: '3', checked: false, startTrainTime: '', endTrainTime: '', status: '' },
    { label: '四', value: '4', checked: false, startTrainTime: '', endTrainTime: '', status: '' },
    { label: '五', value: '5', checked: false, startTrainTime: '', endTrainTime: '', status: '' },
    { label: '六', value: '6', checked: false, startTrainTime: '', endTrainTime: '', status: '' },
    { label: '日', value: '0', checked: false, startTrainTime: '', endTrainTime: '', status: '' },
  ]);
  useEffect(() => {
    if (isModalOpen) {
      console.log(weekData, '打印看看');
    }
  }, [isModalOpen]);

  // useEffect(() => {
  //   const arr = [

  //   ];
  //   setWeekList(arr);
  // }, []);
  const openModal = () => {
    weekList.forEach((el) => {
      if (!el.checked) {
        el.startTrainTime = '';
        el.endTrainTime = '';
      }
    });
    setIsModalOpen(true);
  };
  useEffect(() => {
    if (value) {
      const selectVal: string[] = [];
      const weekDateArr = value?.map((el) => {
        selectVal.push(String(el.value));
        let label = '';
        switch (+el.value) {
          case 1:
            label = '一';
            break;
          case 2:
            label = '二';
            break;
          case 3:
            label = '三';
            break;
          case 4:
            label = '四';
            break;
          case 5:
            label = '五';
            break;
          case 6:
            label = '六';
            break;
          case 0:
            label = '日';
            break;
        }
        return {
          label: label,
          value: el.value,
          startTrainTime: el.startTrainTime,
          endTrainTime: el.endTrainTime,
        };
      });
      setWeekData(weekDateArr || []);
      console.log('====selectVal===', selectVal);
      if (weekList && value) {
        weekList.map((week) => {
          if (selectVal.includes(week.value)) {
            console.log('====inclue===', week.value);
            week.checked = true;
            week.startTrainTime = value.filter((v) => v.value == week.value)[0]?.startTrainTime;
            week.endTrainTime = value.filter((v) => v.value == week.value)[0]?.endTrainTime;
          }
        });
        console.log('===weekList===', weekList);
        setWeekList([...weekList]);
      }
    }
  }, [value]);
  const columns = [
    {
      title: '培训日',
      dataIndex: 'studyday',
      key: 'studyday',
      width: 300,
      render: (_: any, record: any) => <div>周{record.label}</div>,
    },
    {
      title: '时间',
      dataIndex: 'studyTime',
      key: 'studyTime',
      width: 400,
      render: (_: any, record: any) => (
        <div>
          {getUpDownDay(record.startTrainTime, 1)}
          {record.startTrainTime}——{getUpDownDay(record.endTrainTime, 1)}
          {record.endTrainTime}
        </div>
      ),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 300,
      render: (_: any, record: any, index: number) => (
        <div>
          <Button type="text" onClick={() => openModal()}>
            <a>编辑</a>
          </Button>
          <Button
            type="text"
            onClick={() => {
              const list = weekData;
              list.splice(index, 1);
              setWeekData(list.slice());
              const newarr = weekList;
              newarr.forEach((el) => {
                if (el.label === record.label) el.checked = false;
              });
              setWeekList(newarr.slice());
              onChange?.(list);
            }}
          >
            <a>删除</a>
          </Button>
        </div>
      ),
    },
  ];
  const handleOk = () => {
    console.log(weekList, '打印看看周期arr');
    const arr: any[] = weekList.filter((el) => {
      return el.checked;
    });
    if (arr.length < 1) return message.error('请至少选择一个培训日期');

    const list = weekList;
    list.forEach((el) => {
      if (el.checked && (!el.startTrainTime || !el.endTrainTime)) el.status = 'error';
    });
    setWeekList(list.slice());

    const hasVoidSel = arr.some((el) => {
      return !el.startTrainTime || !el.endTrainTime;
    });
    if (hasVoidSel) return message.error('请选择培训时间');
    const hasEquelSel = arr.some((el) => {
      return el.startTrainTime == el.endTrainTime;
    });
    if (hasEquelSel) return message.error('开始结束时间不能相等');
    setWeekData(arr);
    setTableKey(++tableKey);
    console.log(arr, '打印看看数据是多少');
    console.log(arr, '打印看看实际数据');
    setIsModalOpen(false);
    onChange?.(arr);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  return (
    <div>
      {weekData.length > 0 ? (
        <Table key={tableKey} columns={columns} dataSource={weekData} pagination={false} />
      ) : (
        <Button style={{ marginBottom: 15 }} onClick={() => openModal()}>
          添加
        </Button>
      )}
      <YmDialog
        title="培训日期与时间"
        centered
        width={480}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        onClose={handleCancel}
        destroyOnClose={true}
      >
        <div className={OStyle.week_cont}>
          <div className={OStyle.label_cont}>工作日：</div>
          <div className={OStyle.manin_cont}>
            {weekList.map((el, index) => {
              return (
                <div key={el.value} style={{ marginBottom: index !== weekList.length - 1 ? 24 : 0 }}>
                  <Checkbox
                    checked={el.checked}
                    onChange={(e) => {
                      const list = weekList;
                      list[index].checked = e.target.checked;
                      setWeekList(list.slice());
                    }}
                  >
                    星期{el.label}
                  </Checkbox>
                  <TimePicker.RangePicker
                    style={{ marginLeft: 20, width: 276 }}
                    value={
                      weekList[index].startTrainTime
                        ? [dayjs(weekList[index].startTrainTime, 'HH:mm'), dayjs(weekList[index].endTrainTime, 'HH:mm')]
                        : undefined
                    }
                    onChange={(time1: any, time2: any) => {
                      const list = weekList;
                      list[index].startTrainTime = time2[0];
                      list[index].endTrainTime = time2[1];
                      setWeekList(list.slice());
                    }}
                    onFocus={() => {
                      const list = weekList;
                      list[index].status = '';
                      setWeekList(list.slice());
                      el.status = '';
                    }}
                    format={'HH:mm'}
                    status={el.status}
                  />
                </div>
              );
            })}
          </div>
        </div>
      </YmDialog>
    </div>
  );
};
export default SelectWeekDays;
